var hasErrorAfterSaving = false;
var needToGoBackPriorSeletedRow = false;
var saveButton;
var currentPage = { NumberPosition: '1' };
var updateData = false;

//----------TRACKING DATA CHANGE-----------------------------------

function WarningUnsavedata() {
    var result = confirm('Some data has just been changed but not saved. Do you want to save the changes?');
    if (result == true) {
        saveButton.trigger('click');
    }
    else {
        ResetAllFlags();
    }
}

//register the event when page is loaded.
function RegisterBeforeUnload(window) {
    $(window).bind("beforeunload", function () {
        if (HasDataChangedInPage()) {
            WarningUnsavedata();
            if (hasErrorAfterSaving == true) {
                return 'All data that you have entered will be lost because saving is not success!';
            }
        }
    });
}

//overwrite the function
function RegisterClearButtonInScreen(btn, selectedRowId, FillData) {
    $(btn).click(function () {
        systemChange = true;
        //RESET DATA
        if (HasDataChangedInPage()) {
            WarningUnsavedata();
            // If user changed data and accept save but fail,
            // system will not clear data of input controls
            if (hasErrorAfterSaving == true) {
                return;
            }
        }
        selectedRowId.Id = '-1';
        ShowHideValidationSummary(false);
        FillData();
        ResetAllFlags();
        systemChange = false;
    });
};

//when user go to child form or back to parent form, the function will be overwrited
function SetSaveButtonForUnloadEvent(btn) {
    saveButton = $(btn);
}
//when user go to child form or back to parent form, the function will be overwrited
function RegisterSaveButtonInScreen(btn, list, urlForSavingAction, selectedRowId, BuildModel, entityName, HandleAfterSave) {
    SetSaveButtonForUnloadEvent(btn);
    $(btn).click(function () {
        var model = BuildModel();
        if (model != null) {
            SaveData(list, urlForSavingAction, selectedRowId, model, entityName, HandleAfterSave);
        }
        else {
            alert('No data was changed so could not save.');
        }
    });
}

//reset all variables of tracking data change event
function ResetAllFlags() {
    MarkNoDataChangedInPage();
    hasErrorAfterSaving = false;
    needToGoBackPriorSeletedRow = false;
    updateData = false;
}

function SaveData(list, actionUrl, selectedRowId, model, entityName, HandleAfterSave) {
    $.ajax({
        type: "POST",
        dataType: 'json',
        contentType: 'application/json',
        data: JSON.stringify(model),
        url: actionUrl,
        success: function (result) {
            var r = '' + result;
            if (r.indexOf('validation-summary-errors') > 0) {
                hasErrorAfterSaving = true;
                $("#ValidationSummary").html(r).show();
            }
            else {
                if (HandleAfterSave != null) HandleAfterSave();
                ResetAllFlags();
                ShowHideValidationSummary(false);
                alert(entityName + ' successfully saved.');
                selectedRowId.Id = r;
                updateData = true;
                $(list).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
                updateData = false;
            }
        },
        error: function (err) {
            hasErrorAfterSaving = true;
            HandleError(err, "Saving", "");
        },
        async: false
    });
}

function TriggerReloadDataGrid(list) {
    ShowHideValidationSummary(false);

    $(list).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
}

function GridLoadComplete(list, selectedRowId) {
    $(list).jqGrid('setSelection', selectedRowId.Id);
}

function SelectRowOnGrid(rowId, selectedRowId, FillData, list) {
    if (HasDataChangedInPage()) {
        WarningUnsavedata();
        if (hasErrorAfterSaving == true) {
            needToGoBackPriorSeletedRow = true;
            $(list).jqGrid('setGridParam', { setSelection: selectedRowId.Id }).trigger('reloadGrid');
            return;
        }
    }
    selectedRowId.Id = rowId;
    ShowHideValidationSummary(false);
    systemChange = true;
    FillData();
    ResetAllFlags();
    systemChange = false;
}

function HandleError(err, action, entityName) {
    var responseText = '' + err.responseText;
    if (responseText.indexOf('!DOCTYPE html PUBLIC') > 0) {
        //Get Error from responseText
        var errorString = $('#errorString', $(responseText)).html();
        $("#ValidationSummary").html(errorString).show();
    }
    else {
        //alert(err.status + " - " + err.statusText + "\n\n Action: " + action + " " + entityName);
    }
}

function GetPostData(list) {
    return {
        sortName: function () { return $(list).jqGrid('getGridParam', 'sortname'); },
        sortOrder: function () { return $(list).jqGrid('getGridParam', 'sortorder'); },
        rowNumber: function () { return $(list).jqGrid('getGridParam', 'rowNum'); },
        rowId: function () {
            return (updateData == true ? selectedRowId.Id : -1);
        },
        page: function () { return $(list).jqGrid('getGridParam', 'page'); }
    };
}


function SetupGrid(gridOptions, GetColumnNames, GetColumnModel, selectedRowId, idsOfSelectedRows, fnFillData, postData, fnWarningSaveChangedData, fnLoadCompleted) {
    //Set options for grid
    if (gridOptions == null) {
        gridOptions = new Object();
        gridOptions.Id = "listGrid";
        gridOptions.Url = "#";
        gridOptions.Pager = "pagerGrid";
        gridOptions.IsAutoWidthColumn = true;
        gridOptions.IsMultiSelect = false;
        gridOptions.ColumnKeyIndex = "Id";
        gridOptions.DefaultSortName = "Id";
        gridOptions.DefaultSortType = "int";
        gridOptions.DefaultSortOrder = "asc";
    }

    //Configs grid
    $(gridOptions.Id).jqGrid({
        url: gridOptions.Url,
        datatype: "json",
        mtype: "post",
        postData: postData ? postData : GetPostData(gridOptions.Id),

        // Specify the column names
        colNames: GetColumnNames(),
        // Configure the columns
        colModel: GetColumnModel(),
        ignoreCase: true,
        loadonce: false, // Load once all data
        rowNum: 10,
        rowList: [10, 20, 30],
        pager: gridOptions.Pager,
        viewrecords: true,
        width: '100%',
        height: '100%',
        emptyrecords: "No records to view",
        //autowidth: true,
        //shrink: true,
        rownumbers: false,
        multiselect: gridOptions.IsMultiSelect,
        scrollrows: true,
        sortable: true,
        sortname: gridOptions.DefaultSortName,
        sorttype: gridOptions.defaultSortType,
        sortorder: gridOptions.defaultSortOrder,
        shrinkToFit: true,
		loadui: "disable",
        onSelectRow: function (rowId, isSelected) {
            if (gridOptions.IsMultiSelect) {
                var p = this.p,
                    i = $.inArray(rowId, idsOfSelectedRows);

                if (!isSelected && i >= 0) {
                    idsOfSelectedRows.splice(i, 1); // remove id from the list
                } else if (i < 0) {
                    idsOfSelectedRows.push(rowId);
                }
            } else {
                // If this event is fired when user change data in page and move other row in grid
                // and then accept to save data but fail, so system only re-select prior row in grid
                // doesn't need to fill data in controls again
                if (needToGoBackPriorSeletedRow == true) {
                    needToGoBackPriorSeletedRow = false;
                }
                else {
                    // this is normal flow
                    if ((selectedRowId.Id != rowId) || (selectedRowId.Id == rowId && HasDataChangedInPage() == false)) {
                        SelectRowOnGrid(rowId, selectedRowId, fnFillData, gridOptions.Id);
                    }
                }
            }
        },
        loadError: function (xhr, st, str) {
            HandleError(xhr, "Loading", "");
        },
        loadComplete: function (data) {
            currentPage.NumberPosition = $(gridOptions.Id).getGridParam('page');
            if (gridOptions.IsMultiSelect) {
                var grid = jQuery(gridOptions.Id);
                var dataIDs = grid.jqGrid('getDataIDs');

                for (i = 0; i < dataIDs.length; i++) {
                    var index = $.inArray(dataIDs[i], idsOfSelectedRows);
                    if (index > -1) {
                        $(gridOptions.Id).jqGrid('setSelection', dataIDs[i], false);
                    }
                }

            } else {
                GridLoadComplete(gridOptions.Id, selectedRowId);
            }
            //Execute the function which is overwrited each pages
            if (typeof (fnLoadCompleted) == 'function') {
                fnLoadCompleted();
            }
            //Change row's style to zera's style
            $(gridOptions.Id + ' tr').removeClass("ui-widget-content");
            $(gridOptions.Id + ' tr:nth-child(even)').addClass("evenTableRow");
            $(gridOptions.Id + ' tr:nth-child(odd)').addClass("oddTableRow");
        },
        onPaging: function (pgButton) {
            // find out the requested and last page
            var requestedPage = $(gridOptions.Id).getGridParam("page");
            var lastPage = $(gridOptions.Id).getGridParam("lastpage");
            var jumpToPage = ((eval(requestedPage) > eval(lastPage)) ? lastPage : requestedPage);
            var editMode = $(gridOptions.Id).getGridParam('cellEdit');
            if (editMode == true && fnWarningSaveChangedData != null) {
                fnWarningSaveChangedData();
                if (hasErrorAfterSaving == true) {
                    $(gridOptions.Id).setGridParam({ page: currentPage.NumberPosition }); //Workaround - jqGrid still increments the page num even when we return stop so we have to reset it (and track the current page num)    
                    return 'stop';
                }
            }
        },
        async: false
    });
    //Sorting columns
    $("#cb_" + $(gridOptions.Id)[0].id).hide();
    $("#jqgh_" + $(gridOptions.Id)[0].id + "_cb").addClass("ui-jqgrid-sortable");
    cbColModel = $(gridOptions.Id).jqGrid('getColProp', 'cb');
    cbColModel.sortable = true;
    cbColModel.sorttype = function (value, item) {
        return typeof (item.cb) === "boolean" && item.cb ? 1 : 0;
    };
    //Set options for footer
    $(gridOptions.Id).jqGrid('navGrid', gridOptions.Pager, { edit: false, add: false, del: false, beforeRefresh: function () { BeforeRefreshFn(gridOptions.Id) } }, {}, {}, {}, { sopt: ['cn', 'eq', 'lt', 'gt'] });
    //Register event for the button, when user click it, the system will show a popup for user reorder columns.
    $(gridOptions.Id).jqGrid('navButtonAdd', gridOptions.Pager, {
        caption: "",
        title: "Reorder Columns",
        onClickButton: function () {
            jQuery(gridOptions.Id).jqGrid('columnChooser', {
                done: function () { AutoSizeFitGrid(gridOptions.Id, gridOptions.IsAutoWidthColumn); },
                dialog_opts: {
                    create: function () { GeneralColumnReorder(gridOptions.Id, GetColumnModel) },
                    modal: true,
                    minWidth: 470,
                    show: 'blind',
                    hide: 'explode'
                }
            });
        }
    });

    //After setup grid is completed, execute AutoSizeFitGrid function to fit screen of grid
    AutoSizeFitGrid(gridOptions.Id, gridOptions.IsAutoWidthColumn);
    //Register button of map panel on the right screen.
    $('#toggle-east').bind('click', function () {
        AutoSizeFitGrid(gridOptions.Id, gridOptions.IsAutoWidthColumn);
    });
    $('#icoShowTable').bind('click', function () {
        AutoSizeFitGrid(gridOptions.Id, gridOptions.IsAutoWidthColumn);
    });
}

function AutoSizeFitGrid(list, isAutoWidthColumn) {
    if (typeof isAutoWidthColumn == 'undefined')
        isAutoWidthColumn = false;
    //Grid will automatic resize by screen.
    $(list).fitWidthSizeGrid({ base: '.grid', offset: -20, id: list, isAutoWidthColumn: isAutoWidthColumn });
}

//Fix problem of gird : When user clicks refresh button, the search popup doesn't clear info of user input
function BeforeRefreshFn(list) {
    var name_grid = list.replace('#', '');
    $('#fbox_' + name_grid + '_reset').click();
}

//when columnChooser function is executed, all columns will be loaded in popup.
//the function will be used for removing columns have to reorder property is false
function GeneralColumnReorder(list, GetColumnModel) {
    var columnReorder = GetColumnModel();
    var listColRemove = new Array();

    for (var i = 0; i < columnReorder.length; i++) {
        var isHidden = (typeof columnReorder[i].hidden == "undefined") ? false : columnReorder[i].hidden;
        if (isHidden) {
            listColRemove.push(i);
        }
    }

    for (var z = 0; z < listColRemove.length; z++) {
        $('#colchooser_' + $(list)[0].id + ' select option[value="' + listColRemove[z] + '"]').remove();
    }

}

/*
*    SUPPORT FUNCTIONS
**/

function LoadJsonDataForGrid(selector, mydata) {
    for (var i = 0; i <= mydata.length; i++)
        jQuery(selector).jqGrid('addRowData', i + 1, mydata[i]);
}


//Support get list of ids when grid can multi-select
function GetListIDBySelected(list) {
    var ids = jQuery(list).jqGrid('getGridParam', 'selarrrow');
    return ids;
}

//the function will be used for grid which can editabled
function Regis(next, SaveEditValueInCurrentCell) {
    $(next).click(function () {
        SaveEditValueInCurrentCell();
    });
}

function RegisterOnAfterSaveCellInGrid(list, DoOnAfterSaveCell) {
    $(list).setGridParam({
        afterSaveCell: DoOnAfterSaveCell
    });
}

function SetUrlForGrid(list, urlAction) {
    $(list).setGridParam({ url: urlAction });
    TriggerReloadDataGrid(list);
}


function SetHeightOfGrid(list, height) {
    $(list).setGridHeight(height);
}
function SetWidthOfGrid(list, width) {
    $(list).setGridWidth(width, false);
}

function SetEditableGrid(list, afterEditCellFunc) {
    $(list).setGridParam({
        cellEdit: true,
        cellsubmit: 'clientArray',
        afterEditCell: afterEditCellFunc
    });
}

function SetSaveEditableGrid(list, afterSaveCellFunc) {
    $(list).setGridParam({
        cellEdit: true,
        cellsubmit: 'clientArray',
        afterSaveCell: afterSaveCellFunc
    });
}

function RegisterOnBeforeEditCell(list, onBeforeEditCellFunc) {
    $(list).setGridParam({
        beforeEditCell: onBeforeEditCellFunc
    });
}

function GetSelectedRowId(list) {
    return $(list).jqGrid('getGridParam', 'selrow');
}

function GetRowId(list, columnIdName) {
    var grid = jQuery(list);
    var sel_id = grid.jqGrid('getGridParam', 'selrow');
    return grid.jqGrid('getCell', sel_id, columnIdName);
}

function GetCellValue(list, rowId, columnIdName) {
    var rowData = jQuery(list).getRowData(rowId);
    return rowData[columnIdName];
}

/* tdoan5 */
function GetValuesOfSelectedCol(selector, columName) {
    var manholeIDs = new Array();
    var col = jQuery(selector).jqGrid('getCol', columName, true);
    for (var i = 0; i < col.length; i++) {
        manholeIDs[i] = col[i].value;
    }
    return manholeIDs.join(",");
}

function DeleteRows(selector, ids) {
    var list = ids.split(',');    
    for (var i = 0; i < list.length; i++) {
        var col = jQuery(selector).jqGrid('delRowData', list[i]);
    }
}

function DeleteRow(selector, id) {
    selector.jqGrid('delRowData', id);
}

function CountRecords(selector) {
    return selector.getGridParam("reccount");
}

function SumValuesCol(selector, columnName) {
    return selector.jqGrid('getCol', columnName, false, 'sum');
}
// Copy Data to Gird
function LoadDataForGrid(selector, mydata) {
    for (var i = 0; i <= mydata.length; i++)
        jQuery(selector).jqGrid('addRowData', i + 1, mydata[i]);
}

function ReloadGridView(selector, actionUrl, opts) {
    var grid = $(selector);
    grid.clearGridData();
    grid.setGridParam({ url: actionUrl });
    grid.setGridParam({ postData: opts });
    grid.setGridParam({ datatype: 'json' });
    grid.trigger('reloadGrid');
}   